package cn.school.controller.educational;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.school.common.api.CommonPage;
import cn.school.common.api.CommonResult;
import cn.school.common.utils.SysUserUtils;
import cn.school.educational.entity.TeachingMaterial;
import cn.school.educational.entity.TeachingMaterialStoreDetils;
import cn.school.educational.service.TeachingMaterialService;
import cn.school.educational.service.TeachingMaterialStoreDetilsService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@Api(tags = "educational-teachingMaterial-StoreDetils => 教材库存明细")
@RequestMapping("/educational/teachingMaterial/storeDetils")
public class TeachingMaterialStoreDetilsController {
    @Autowired
    private TeachingMaterialStoreDetilsService teachingMaterialStoreDetilsService;
    @Autowired
    private TeachingMaterialService teachingMaterialService;


    @ApiOperation("获取列表")
    @GetMapping("/list")
    public CommonResult<CommonPage<TeachingMaterialStoreDetils>> list(@RequestParam Map<String, Object> para) {
        int pageNum = Integer.parseInt((String) para.get("pageNum"));
        int pageSize = Integer.parseInt((String) para.get("pageSize"));
        String beginTime = (String) para.get("beginTime");
        String endTime = (String) para.get("endTime");
        String temaId = (String) para.get("temaId");

        // 分页条件
        Page<TeachingMaterialStoreDetils> page = new Page<>();
        page.setSize(pageSize);
        page.setCurrent(pageNum);

        // 搜索条件
        LambdaQueryWrapper<TeachingMaterialStoreDetils> queryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotEmpty(temaId)) {
            queryWrapper.eq(TeachingMaterialStoreDetils::getTemaId, temaId);
        }
        if (StrUtil.isNotEmpty(beginTime)) {
            queryWrapper.ge(TeachingMaterialStoreDetils::getCreateTime, DateUtil.parse(beginTime + " 00:00:00", "yyyy-MM-dd HH:mm:ss"));
        }
        if (StrUtil.isNotEmpty(endTime)) {
            queryWrapper.le(TeachingMaterialStoreDetils::getCreateTime, DateUtil.parse(endTime + " 23:59:59", "yyyy-MM-dd HH:mm:ss"));
        }
        queryWrapper.eq(TeachingMaterialStoreDetils::getTenantId, SysUserUtils.getSysUser().getTenantId());
        // 排序条件
        queryWrapper.orderByDesc(TeachingMaterialStoreDetils::getCreateTime);
        queryWrapper.orderByDesc(TeachingMaterialStoreDetils::getTemaId);

        IPage<TeachingMaterialStoreDetils> iPage = this.teachingMaterialStoreDetilsService.page(page, queryWrapper);
        if (iPage.getRecords() != null && iPage.getRecords().size() != 0) {
            List<Long> temaIdList = iPage.getRecords().stream().map(TeachingMaterialStoreDetils::getTemaId).collect(Collectors.toList());
            // 去重
            LinkedHashSet<Long> hashSet = new LinkedHashSet<>(temaIdList);
            temaIdList = new ArrayList<>(hashSet);
            // 获取对应教材的名称
            List<TeachingMaterial> temaList = this.teachingMaterialService.listByIds(temaIdList);
            HashMap<Long, TeachingMaterial> temaMap = (HashMap<Long, TeachingMaterial>) temaList.stream().collect(Collectors.toMap(TeachingMaterial::getId, obj -> obj));
            for (TeachingMaterialStoreDetils record : iPage.getRecords()) {
                if (temaMap.containsKey(record.getTemaId())) {
                    record.setTemaName(temaMap.get(record.getTemaId()).getTemaName());
                    record.setTemaCode(temaMap.get(record.getTemaId()).getTemaCode());
                }
            }
        }

        return CommonResult.success(CommonPage.restPage(iPage));
    }


    @ApiOperation("获取单个教材的入/出库的明细")
    @GetMapping("/info/{id}")
    public CommonResult<TeachingMaterialStoreDetils> getInfoById(@PathVariable Long id) {
        TeachingMaterialStoreDetils subject = this.teachingMaterialStoreDetilsService.getById(id);
        return CommonResult.success(subject);
    }


    @ApiOperation("添加入/出库记录")
    @PostMapping("/add")
    public CommonResult<TeachingMaterialStoreDetils> add(@RequestBody TeachingMaterialStoreDetils teachingMaterial) {
        LambdaQueryWrapper<TeachingMaterialStoreDetils> queryWrapper = new LambdaQueryWrapper<>();
        teachingMaterial.setCreateBy(SysUserUtils.getSysUser().getId());
        teachingMaterial.setCreateTime(Calendar.getInstance().getTime());
        teachingMaterial.setModifyTime(Calendar.getInstance().getTime());
        boolean isAddSuccess = this.teachingMaterialStoreDetilsService.saveBiz(teachingMaterial);
        if (isAddSuccess) {
            return CommonResult.success();
        } else {
            return CommonResult.failed();
        }
    }


    @ApiOperation("教材下拉搜索条件")
    @PostMapping("/temaList")
    public CommonResult<List<TeachingMaterial>> temaList(@RequestBody TeachingMaterial teachingMaterial) {
        LambdaQueryWrapper<TeachingMaterial> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TeachingMaterial::getTenantId, SysUserUtils.getSysUser().getTenantId());
        if (StrUtil.isNotEmpty(teachingMaterial.getTemaName())) {
            queryWrapper.like(TeachingMaterial::getTemaName, teachingMaterial.getTemaName()).or(
                    wrapper -> {
                        wrapper.like(TeachingMaterial::getTemaCode, teachingMaterial.getTemaName());
                    }
            );
        }

        Page<TeachingMaterial> page = new Page<>();
        page.setCurrent(1);
        page.setSize(100);
        page = this.teachingMaterialService.page(page, queryWrapper);
        return CommonResult.success(page.getRecords());
    }


}
